<script lang="jsx">
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import LowP from "~/views/low/P.vue";
import { SignIn, SetIp, SetVisitor, initLoginlog, GetVersion } from "~/api";
import { connectSocket } from "~/utils/socket";
import timeExit from "~/utils/timeExit";

export default defineComponent({
    async setup() {
        const pageStore = usePageStore();
        const userStore = useUserStore();
        const dialogStore = useDialogStore();
        const cacheStore = useCacheStore();
        const backTopVisible = ref(false);
        const digitalPeopleRef = ref(null);
        const route = useRoute();
        let timer = null;

        if (process.server) {
            useHead({
                script: [
                    {
                        innerHTML: `
                            var _ssrTime_ = ${Date.now()}
                        `,
                    },
                ],
            });
            const headers = useRequestHeaders();
            const userAgent = headers["user-agent"];

            pageStore.isMobile =
                /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
                    userAgent
                );

            pageStore.isVideoError = /XiaoMi|Miui/i.test(userAgent);

            pageStore.isIe =
                userAgent.indexOf("MSIE ") > -1 ||
                userAgent.indexOf("Trident/") > -1;

            if (/Chrome/i.test(userAgent)) {
                const chromeVersion = userAgent.match(/Chrome\/([\d.]+)/)[1];
                if (parseInt(chromeVersion) < 60) {
                    return () => <LowP />;
                }
            }
        }

        if (process.client) {
            const { version: serverVersion } = await GetVersion();

            if (process.env.NODE_ENV === "production") {
                SetIp();

                if (userStore.isLogin) {
                    timeExit();
                }
            }

            window.addEventListener("beforeunload", (event) => {
                let residenceTime = pageStore.residenceTime;
                let stayTime = (
                    (Date.now() - residenceTime.startTime) /
                    1000
                ).toFixed(2);

                let data = JSON.stringify({
                    name: residenceTime.name,
                    consumer_id: userStore.userInfo.id || "",
                    begin_time: parseInt(residenceTime.startTime / 1000),
                    duration_of_stay: stayTime,
                });
                const blob = new Blob([data], { type: "application/json" });

                navigator.sendBeacon("/api/user/user_residence_time", blob, {
                    type: "beacon",
                });
            });

            if (!navigator.cookieEnabled) {
                Message().warning("当前浏览器已禁用cookie，请启用cookie后重试");
            }

            if (process.env.NODE_ENV === "development") {
                if (VConsole && pageStore.isMobile) {
                    new VConsole();
                }
            }

            if (process.client) {
                if (window._v_ != serverVersion) {
                    reloadNuxtApp();
                }
            }


            // 去除警告
            console.warn = function () { };

            if (pageStore.isMobile) {
                document.body.classList.add("m-body");
                if (IsWeiXin()) {
                    const return_url = location.href;
                    const parmas = new URLSearchParams(location.search);
                    const pageStore = usePageStore();
                    if (parmas.has("code")) {
                        const code = parmas.get("code");
                        pageStore.code = code;
                    } else {
                        const appId = "wxc0542623380dd621";
                        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(
                            return_url
                        )}&response_type=code&scope=snsapi_base#wechat_redirect`;
                    }
                }
            } else {
                document.body.classList.add("p-body");
            }

            window.addEventListener("scroll", () => {
                backTopVisible.value = true;
                clearTimeout(timer);
                timer = setTimeout(() => {
                    backTopVisible.value = false;
                }, 5000);
            });

            if (process.env.NODE_ENV === "production") {
                if (
                    route?.path?.indexOf("caseView") === -1 &&
                    route?.path?.indexOf("login") === -1 &&
                    route?.path?.indexOf("register") === -1 &&
                    !IsWeiXin() &&
                    !IsAlipay()
                ) {
                    addBaiduCustomer();
                }
            }

            connectSocket();

            if (userStore.isLogin) {
                setTimeout(() => {
                    SignIn().then((res) => {
                        if (res.code == 200) {
                            dialogStore.isSignInDialogVisible = true;
                        }
                    });
                }, 1000);

                initLoginlog();
                if (process.env.NODE_ENV === "production") {
                    HAS_NEW_MESSAGE();
                }
                NoticeTips();
            } else {
                // 记录访客
                SetVisitor();
            }

            onMounted(async () => {
                if (process.client) {
                    if (window._v_ == serverVersion) {
                        if (Date.now() - _ssrTime_ > 60 * 1000) {
                            setTimeout(() => {
                                cacheStore.setKey(String(Date.now()));
                            })
                        }
                    }
                }
            })
        }

        if (pageStore.isMobile) {
            if (process.client) {
                // 获取用户Token信息
                // 获取用户头像
                if (userStore.isLogin) {
                    GET_USERINFO();
                    GET_AVATAR();
                    GET_MIDNUM();
                }
            }
        } else {
            // 获取用户Token信息
            // 获取用户头像
            if (userStore.isLogin) {
                GET_USERINFO();
                GET_AVATAR();
                GET_MIDNUM();
            }
        }

        return () => (
            <el-config-provider locale={zhCn}>
                {pageStore.isMobile ? (
                    <div class="m-page">
                        <var-style-provider
                            style-vars={{
                                "--button-primary-color": "#5085FB",
                            }}
                        >
                            <NuxtLayout>
                                <NuxtPage />
                            </NuxtLayout>

                            <ClientOnly>
                                {pageStore.baiduCustomer && (
                                    <LazyCustomerServiceM />
                                )}
                                {backTopVisible.value && (
                                    <var-back-top
                                        bottom={20}
                                        right={20}
                                        duration={300}
                                    />
                                )}
                                <LazyDialogBuyProtocolM />
                                <LazyDialogPayServiceM />
                                <LazyDialogPayM />
                                <LazyDialogShareTemplateM />
                                <LazyDialogCommentListWorkM />
                                <LazyDialogCommentListCaseM />
                                <LazyDialogMidListM />
                                <LazyDialogTaskListM />
                                <LazyDialogScoreSuccessM />
                                <LazyDialogSignInM />
                                <LazyDialogScoreLotteryM />
                                <LazyDialogScoreLotterySuccessM />
                                <LazyDialogScoreLotteryFailM />
                                <LazyDialogEditorUpdateTipsM />
                                <LazyDialogNoticeTipsM />
                                {/* <LazyDigitalPeopleM /> */}

                                <LazyDialogTicketReceiveM />
                            </ClientOnly>
                        </var-style-provider>
                    </div>
                ) : (
                    <div class="app-page">
                        <NuxtLayout>
                            <NuxtPage />
                        </NuxtLayout>
                        <ClientOnly>
                            {/* <LazyDialogLoginTipsP /> */}
                            <LazyDialogBuyProtocolP />
                            <LazyDialogPayServiceP />
                            <LazyDialogPayP />
                            <LazyDialogShareTemplateP />
                            <LazyDialogCommentListWorkP />
                            <LazyDialogCommentListCaseP />
                            <LazyDialogMidListP />
                            <LazyDialogTaskListP />
                            <LazyDialogScoreSuccessP />
                            <LazyDialogSignInP />
                            <LazyDialogScoreLotteryP />
                            <LazyDialogScoreLotterySuccessP />
                            <LazyDialogScoreLotteryFailP />
                            <LazyDigitalPeopleP ref={digitalPeopleRef} />
                            <LazyDialogNoticeTipsP />
                            <LazyDialogReleaseNoteP />
                            {/* <LazyDialogSearchP /> */}

                            <LazyDialogTicketReceiveP />
                            <LazyDialogLoginModalP />
                        </ClientOnly>
                    </div>
                )}
            </el-config-provider>
        );
    },
});
</script>
<style lang="scss">
@font-face {
    font-family: "DINCond_Regular";
    src: url("https://yzpt-resources.oss-cn-hangzhou.aliyuncs.com/web/font/DINCond_Regular.woff");
}

#__nuxt {
    width: 100%;
    height: 100%;
}

.m-page {
    width: 100%;
    height: 100%;
}

.m-page * {
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

.app-page {
    min-width: 1200px;
}

.m-body #newBridge,
.m-body #aff-im-root {
    display: none !important;
}

.var-style-provider {
    width: 100%;
    height: 100%;
}

.var-action-sheet .var-action-sheet__action-name {
    overflow: hidden !important;
}

.var-action-sheet .var-action-sheet__action-icon[var-action-sheet-cover] {
    margin-right: 10px;
}

.embed-messageboard-base {
    display: none !important;
}

.embed-chat-container {
    margin-right: 40px;
}
</style>
